// 引入工具
import { checkUserData } from '~/assets/js/util'

const state = { // 存放数据
  userData: checkUserData()
}

const mutations = { // 修改 state，包含同步操作，this.$store.commit('setUserDataMutation') 触发
  setUserDataMutation(state, data) {
    // 保存用户信息到 localStorage
    localStorage.removeItem('userData')
    localStorage.setItem('userData', JSON.stringify(data))
    state.userData = data
  },
  updateUserDataMutation(state, data) {
    // 保存用户信息到 localStorage
    const newUserData = Object.assign(state.userData, data)
    localStorage.setItem('userData', JSON.stringify(newUserData))
    state.userData = newUserData
  },
  removeUserDataMutation(state) {
    localStorage.removeItem('userData')
    state.userData = null
  }
}

const actions = { // 修改 context，可以包含异步操作，this.$store.dispatch('updateUserDataAction') 触发
  async updateUserDataAction(context, userToken) {
    try {
      // 请求登录用户数据
      const userData = await this.$request({
        url: 'user/userPersonalCenterInfo',
        method: 'get',
        token: userToken,
        context: this
      })
      userData.userToken = userToken
      // 保存用户信息到 state
      context.commit('setUserDataMutation', userData)
    } catch (e) {
      console.log(e)
    }
  }
}

export default {
  state,
  mutations,
  actions
}
